package com.cafe.pro.manager;

import com.cafe.pro.config.CafeConfig;
import com.cafe.pro.util.CryptoUtils;
import com.cafe.pro.util.KeyUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.security.*;

@Component
@AllArgsConstructor
public class KeyManager {
    private final CafeConfig cafeConfig;

    private PrivateKey getPrivateKey() throws Exception {
        return KeyUtil.parseKeyPair(cafeConfig.getRsaKeyPair()).getPrivate();
    }

    public PublicKey getPublicKey() throws Exception {
        return KeyUtil.parseKeyPair(cafeConfig.getRsaKeyPair()).getPublic();
    }

    public String getAesKey(String version) throws Exception {
        String encryptedKey = cafeConfig.getAseKeyPairs().get(version);
        return CryptoUtils.decryptWithRsa(encryptedKey, getPrivateKey());
    }

    public String getAesKey() throws Exception {
        return getAesKey(getCurrentKeyVersion());
    }

    public String getCurrentKeyVersion() {
        return cafeConfig.getCurrentKeyVersion();
    }

}
